package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.PlatformQQuestion;
import com.ruoyi.teaching.domain.UniversalCreateUpdate;
import com.ruoyi.teaching.domain.vo.PlatformQKnowledgeVO;
import com.ruoyi.teaching.domain.vo.PlatformQQuestionVO;
import com.ruoyi.teaching.mapper.PlatformQKnowledgeMapper;
import com.ruoyi.teaching.mapper.PlatformQQuestionMapper;
import com.ruoyi.teaching.service.PlatformQQuestionService;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-06-12
 */
@Service
public class PlatformQQuestionServiceImpl extends ServiceImpl<PlatformQQuestionMapper, PlatformQQuestion> implements PlatformQQuestionService {
    @Autowired
    private PlatformQQuestionMapper platformQQuestionMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private PlatformQKnowledgeMapper platformQKnowledgeMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public AjaxResult selectPlatformQQuestionById(Long id) {
        PlatformQQuestion platformQQuestion = platformQQuestionMapper.selectById(id);
        PlatformQQuestionVO platformQQuestionVO = UniversalUtil.stringToArray(platformQQuestion);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformQQuestionVO);
    }

    @Override
    public AjaxResult selectPlatformQQuestionListInQuestion(Integer questionType, String questionName, Integer pageNum, Integer pageSize, Integer knowledgeId) {
        // int userId = SecurityUtils.getUserId().intValue();
        QueryWrapper<PlatformQQuestion> queryWrapper = buildQueryWrapper(questionType, questionName, null, null, knowledgeId);
        if(null == queryWrapper){
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功");
        }
        return executeQueryAndBuildResult(pageNum, pageSize, queryWrapper);
    }

    @Override
    public AjaxResult selectPlatformQQuestionListInExam(Integer questionType, String questionName, Integer pageNum, Integer pageSize, String knowledgeName) {
        QueryWrapper<PlatformQQuestion> queryWrapper = buildQueryWrapper(questionType, questionName, null, knowledgeName,null);
        if(null == queryWrapper){
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功");
        }
        return executeQueryAndBuildResult(pageNum, pageSize, queryWrapper);
    }

    private QueryWrapper<PlatformQQuestion> buildQueryWrapper(Integer questionType, String questionName, Integer userId, String knowledgeName, Integer knowledgeId) {
        QueryWrapper<PlatformQQuestion> queryWrapper = new QueryWrapper<>();

        // 根据题目类型进行筛选
        if (questionType != null) {
            queryWrapper.eq("question_type", questionType);
        }

        // 根据题目名称进行模糊查询
        if (questionName != null && !questionName.isEmpty()) {
            queryWrapper.like("question_name", questionName);
        }

        // 根据创建者ID进行筛选
        if (userId != null) {
            queryWrapper.eq("create_id", userId);
        }

        // 根据知识点ID进行筛选
        if (knowledgeId != null && knowledgeId != 0) {
            queryWrapper.eq("knowledge_id", knowledgeId);
        }else {
            if(null == userId){
                 userId = Math.toIntExact(SecurityUtils.getUserId());
            }
            Long deptId = sysUserMapper.selectUserById(Long.valueOf(userId)).getMajorId();
            String specialtyName = deptMapper.selectDeptById(deptId).getDeptName();

            //查询所有学校当前专业下的知识点
            Long[] deptIds = deptMapper.selectDeptIdByName(specialtyName);
            List<PlatformQKnowledgeVO> platformQKnowledges = platformQKnowledgeMapper.selectKnowledgeListBySpecialtyId(deptIds);
            // 使用 Java 流去重
            Map<String, PlatformQKnowledgeVO> uniqueKnowledgeMap = platformQKnowledges.stream()
                    .collect(Collectors.toMap(
                            PlatformQKnowledgeVO::getKnowledgeName,
                            p -> p,
                            (existing, replacement) -> existing // 如果有重复的knowledgeName，保留第一个出现的
                    ));

            platformQKnowledges = uniqueKnowledgeMap.values().stream().collect(Collectors.toList());
            List<Integer> knowledgeIds = new ArrayList<>();
            platformQKnowledges.forEach(knowledge -> knowledgeIds.add(knowledge.getId()));
            if(!CollectionUtils.isEmpty(knowledgeIds)){
                queryWrapper.in("knowledge_id", knowledgeIds);
            }else {
                //有知识点才会有题目，这里的操作为的是返回空题出去
                return null;
            }
        }

        // 根据知识点名称进行筛选
        if (knowledgeName != null && !knowledgeName.isEmpty()) {
            List<Integer> knowledgeIds = platformQKnowledgeMapper.selectKnowledgeIdByName(knowledgeName);
            if (knowledgeIds != null && knowledgeIds.size() > 0) {
                queryWrapper.in("knowledge_id", knowledgeIds);
            }
        }

        // 根据 id 字段倒序排序
        queryWrapper.orderByDesc("id");

        return queryWrapper;
    }

    private AjaxResult executeQueryAndBuildResult(Integer pageNum, Integer pageSize, QueryWrapper<PlatformQQuestion> queryWrapper) {
        // 创建分页对象
        Page<PlatformQQuestion> platformQQuestionPage = new Page<>(pageNum, pageSize);

        // 执行分页查询
        Page<PlatformQQuestion> platformQQuestionPage1 = platformQQuestionMapper.selectPage(platformQQuestionPage, queryWrapper);

        // 获取查询结果
        List<PlatformQQuestion> records = platformQQuestionPage1.getRecords();

        // 创建用于存储VO的分页对象
        Page<PlatformQQuestionVO> platformQQuestionVOPage = new Page<>();
        List<PlatformQQuestionVO> platformQQuestionVOS = new ArrayList<>();

        // 将查询结果转换为VO
        for (PlatformQQuestion record : records) {
            PlatformQQuestionVO platformQQuestionVO = UniversalUtil.stringToArray(record);
            platformQQuestionVOS.add(platformQQuestionVO);
        }

        // 复制分页信息
        BeanUtils.copyProperties(platformQQuestionPage1, platformQQuestionVOPage);
        platformQQuestionVOPage.setRecords(platformQQuestionVOS);

        // 返回查询结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformQQuestionVOPage);
    }


    @Override
    public AjaxResult getCount(List<String> knowledgeNames) {
        // 使用 HashSet 存储知识点 ID，以避免重复
        Set<Integer> knowledgeIds = new HashSet<>();

        // 根据知识点名称查询对应的知识点 ID
        if(!CollectionUtils.isEmpty(knowledgeNames)){
            for (String knowledgeName : knowledgeNames) {
                List<Integer> ids = platformQKnowledgeMapper.selectKnowledgeIdByName(knowledgeName);
                knowledgeIds.addAll(ids);
            }
        }else {
            Long userId = SecurityUtils.getUserId();
            Long deptId = sysUserMapper.selectUserById(userId).getMajorId();
            String specialtyName = deptMapper.selectDeptById(deptId).getDeptName();

            //查询所有学校当前专业下的知识点
            Long[] deptIds = deptMapper.selectDeptIdByName(specialtyName);
            List<PlatformQKnowledgeVO> platformQKnowledges = platformQKnowledgeMapper.selectKnowledgeListBySpecialtyId(deptIds);
            for (PlatformQKnowledgeVO platformQKnowledge : platformQKnowledges) {
                knowledgeIds.add(platformQKnowledge.getId());
            }
        }


        // 存储所有相关的题目
        List<PlatformQQuestion> questions = new ArrayList<>();
        for (Integer knowledgeId : knowledgeIds) {
            List<PlatformQQuestion> platformQQuestions = platformQQuestionMapper.selectByknowledgeId(knowledgeId.longValue());
            questions.addAll(platformQQuestions);
        }

        // 初始化不同题型的统计结果
        Map<Integer, List<PlatformQQuestion>> questionTypeMap = new HashMap<>();
        for (int i = 0; i <= 4; i++) {
            questionTypeMap.put(i, new ArrayList<>());
        }

        // 根据题目类型分类存储题目
        for (PlatformQQuestion question : questions) {
            int questionType = question.getQuestionType();
            questionTypeMap.get(questionType).add(question);
        }

        // 创建返回的统计结果列表
        List<Map<String, Integer>> result = new ArrayList<>();
        for (int i = 0; i <= 4; i++) {
            Map<String, Integer> questionTypeCountMap = new HashMap<>();
            questionTypeCountMap.put("questionType", i);
            questionTypeCountMap.put("questionTypeCount", questionTypeMap.get(i).size());
            result.add(questionTypeCountMap);
        }

        // 返回成功结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", result);
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult insertPlatformQQuestion(List<PlatformQQuestionVO> platformQQuestionVOs) {
        int size = platformQQuestionVOs.size();
        int i = 0;
        UniversalCreateUpdate person = UniversalUtil.getCreateUpdate(sysUserMapper);
        int roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(Long.valueOf(person.getId()))[0]);
        if (roleId != 3) {
            return new AjaxResult(HttpStatus.ERROR, "请使用身份为老师的账号上传题目");
        }
        for (PlatformQQuestionVO platformQQuestionVO : platformQQuestionVOs) {
            PlatformQQuestion platformQQuestion = UniversalUtil.arrayToString(platformQQuestionVO);
            platformQQuestion.setCreateTime(DateUtils.getNowDate());
            platformQQuestion.setCreateId(person.getId());
            platformQQuestion.setCreateBy(person.getName());
            Long userId = SecurityUtils.getUserId();
            int specialtyId = sysUserMapper.selectUserById(userId).getMajorId().intValue();
            platformQQuestion.setSpecialtyId(specialtyId);//当前登录老师是哪个专业的就把题目发布到哪个专业（deptId）
            int insert = platformQQuestionMapper.insert(platformQQuestion);
            if (insert > 0) {
                i++;
            }
        }
        if (size == i) {
            return new AjaxResult(HttpStatus.SUCCESS, "新增成功");
        }
        throw new RuntimeException("新增失败");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult updatePlatformQQuestion(PlatformQQuestionVO platformQQuestionVO) {
        Long userId = SecurityUtils.getUserId();
        PlatformQQuestion platformQQuestion1 = platformQQuestionMapper.selectById(platformQQuestionVO.getId());
        if(null == platformQQuestion1){
            return new AjaxResult(HttpStatus.ERROR, "改题目已被删除，请刷新后重试");
        }
        long l = platformQQuestion1.getCreateId().longValue();
        if (l!= userId) {
            return new AjaxResult(HttpStatus.ERROR, "无法修改他人创建的题目");
        }
        PlatformQQuestion platformQQuestion = UniversalUtil.arrayToString(platformQQuestionVO);
        UniversalCreateUpdate person = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformQQuestion.setUpdateTime(DateUtils.getNowDate());
        platformQQuestion.setUpdateId(person.getId());
        platformQQuestion.setUpdateBy(person.getName());
        int i = platformQQuestionMapper.updateById(platformQQuestion);
        if (i > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "修改成功");
        }
        throw new RuntimeException("修改失败");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deletePlatformQQuestionByIds(Long[] ids) {
        int i = 0;
        for (Long id : ids) {
            i++;
            long l = platformQQuestionMapper.selectById(id).getCreateId().longValue();
            Long userId = SecurityUtils.getUserId();
            if(l != userId){
                if(i == 1){
                    return new AjaxResult(HttpStatus.ERROR, "无法删除他人创建的题目");
                }else {
                    return new AjaxResult(HttpStatus.ERROR, "删除失败，请核对第"+i+"道题目是否是您的创建");
                }
            }
        }
        int length = ids.length;
        int delete = platformQQuestionMapper.deleteBatchIds(Arrays.asList(ids));
        if (length == delete) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            throw new RuntimeException("删除失败");
        }
    }
}
